package com.leisai.manager.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leisai.manager.common.utils.TreeUtil;
import com.leisai.manager.dao.IndustryMapper;
import com.leisai.manager.dao.ReportMapper;
import com.leisai.manager.dao.SalesDataMapper;
import com.leisai.manager.dao.WriteMapper;
import com.leisai.manager.dto.IndustryDTO;
import com.leisai.manager.dto.ReportDTO;
import com.leisai.manager.pojo.Report;
import com.leisai.manager.pojo.SalesData;
import com.leisai.manager.pojo.TreeNode;
import com.leisai.manager.response.PageDataResult;
import com.leisai.manager.service.ReportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: jim
 * @Date: 2021/12/01/15:57
 * @Description:
 */
@Service
public class ReportServiceImpl implements ReportService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ReportMapper reportMapper ;
    @Autowired
    private IndustryMapper industryMapper;
    @Autowired
    private WriteMapper writeMapper;
    @Autowired
    private SalesDataMapper salesDataMapper;
    @Override
    public Map<String, Object> addReport(Report report) {
        Map<String,Object> data = new HashMap();
        try {
            int result = reportMapper.insert(report);
            if(result == 0){
                data.put("code",0);
                data.put("msg","新增失败！");
                logger.error("报表[新增]，结果=新增失败！");
                return data;
            }
            data.put("code",1);
            data.put("msg","新增成功！");
            logger.info("报表[新增]，结果=新增成功！");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("报表[新增]异常！", e);
            return data;
        }
        return data;
    }

    @Override
    public Map<String, Object> updateReport(Report report) {
        Map<String,Object> data = new HashMap();
        try {

            int result = reportMapper.updateByPrimaryKey(report);
            if(result == 0){
                data.put("code",0);
                data.put("msg","更新失败！");
                logger.error("报表[更新]，结果=更新失败！");
                return data;
            }
            data.put("code",1);
            data.put("msg","更新成功！");
            logger.info("报表[更新]，结果=更新成功！");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("报表[更新]异常！", e);
            return data;
        }
        return data;
    }

    @Override
    public PageDataResult getReportList(Integer pageNum, Integer pageSize,ReportDTO reportDTO) {
        PageDataResult pageDataResult = new PageDataResult();
        PageHelper.startPage(pageNum, pageSize);
        List<ReportDTO> reportDTOS = reportMapper.getReportList(reportDTO);

        if(reportDTOS.size() != 0){
            PageInfo<ReportDTO> pageInfo = new PageInfo<>(reportDTOS);
            pageDataResult.setList(reportDTOS);
            pageDataResult.setTotals((int) pageInfo.getTotal());
        }
        return pageDataResult;
    }

    @Override
    public Map<String, Object> del(Integer id) {
        Map<String ,Object> data = new HashMap<>();
        try{
            int result = reportMapper.deleteByPrimaryKey(id);
            if(result == 0){
                data.put("code",0);
                data.put("msg","删除失败");
                logger.error("删除失败");
                return data;
            }
            data.put("code",1);
            data.put("msg","删除成功");
            logger.info("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("删除报表异常！", e);
        }
        return data;
    }

    @Override
    public Report getReportById(Integer id) {
        return reportMapper.selectByPrimaryKey(id);
    }

    @Override
    public Map<String, Object> initReport(ReportDTO reportDTO) {
        Map<String ,Object> data = new HashMap<>();
        try{
            int result = reportMapper.initReport(reportDTO);
            if(result == 0){
                data.put("code",0);
                data.put("msg","初始化报表失败");
                logger.error("初始化报表失败");
                return data;
            }
            data.put("code",1);
            data.put("msg","初始化报表成功");
            logger.info("初始化报表成功");
        }catch (Exception e){
            e.printStackTrace();
            logger.error("初始化报表异常！", e);
        }
        return data;
    }

    @Override
    public JSONArray getIndustryReport(ReportDTO reportDTO) {
        //最上层的行业id
        Integer industryId = reportDTO.getIndustryId();
        String year = reportDTO.getYear();

        IndustryDTO industryDTO = new IndustryDTO();
        industryDTO.setPid(industryId.longValue());
        //第二层的id
        List<IndustryDTO> industryList = industryMapper.getIndustryList(industryDTO);
        if (industryList.size()>0) {
            ArrayList<TreeNode> treeNodes = new ArrayList<>();
            for (IndustryDTO industryDTO1 : industryList) {
                TreeNode treeNode = new TreeNode();
                treeNode.setId(industryDTO1.getIndustryId());
                treeNode.setName(industryDTO1.getIndustryName());
                treeNode.setPid(industryDTO1.getPid().intValue());

                SalesData salesData = new SalesData();
                salesData.setINDUSTRY_ID(industryDTO1.getIndustryId());
                salesData.setYEAR(year);
                SalesData salesData1 = salesDataMapper.selectByAttr(salesData);
                //将销售额存到value中用于做图形展示，将其他参数存储到拓展list中
                treeNode.setValue(salesData1.getSALE_RESULTS());
                Double market_requirement = salesData1.getMARKET_REQUIREMENT();
                Double sale_target = salesData1.getSALE_TARGET();
                Double last_year_sales = salesData1.getLAST_YEAR_SAlES();
                Double market_share = salesData1.getMARKET_SHARE();
                Double sale_completion = salesData1.getSALE_COMPLETION();
                Double growth_rate = salesData1.getGROWTH_RATE();
                Map<String, Object> extendsMap = treeNode.getExtendsMap();
                extendsMap.put("market_requirement", market_requirement);
                extendsMap.put("sale_target", sale_target);
                extendsMap.put("last_year_sales", last_year_sales);
                extendsMap.put("market_share",market_share);
                extendsMap.put("sale_completion",sale_completion);
                extendsMap.put("growth_rate",growth_rate);
                treeNodes.add(treeNode);
            }

            List<TreeNode> build = TreeUtil.build(treeNodes, industryId);
            JSONArray jsonArray = new JSONArray();
            jsonArray.addAll(build);

            return jsonArray;
        }
        return  null;
    }

    @Override
    public JSONObject getIndustrytTree() {
        //所有的行业列表
        List<IndustryDTO> industryList = industryMapper.getIndustryList(new IndustryDTO());
        List<TreeNode> industryTree = new ArrayList<TreeNode>();
        for (IndustryDTO industryDTO:industryList) {
            TreeNode treeNode = new TreeNode();
            treeNode.setName(industryDTO.getIndustryName());
            treeNode.setId(industryDTO.getIndustryId());
            treeNode.setPid(industryDTO.getPid().intValue());
            industryTree.add(treeNode);
        }
        //1是最上层行业的id
        TreeNode build = TreeUtil.build1(industryTree, 1);
        JSONObject json = (JSONObject)JSONObject.toJSON(build);


        return json;
    }

    @Override
    public ReportDTO getReportByObject(ReportDTO dto) {
        return reportMapper.selectOneByAll(dto);
    }

}
